package com.darkness.rpc.registercenter.file;


import com.darkness.rpc.registercenter.Register;
import com.darkness.rpc.registercenter.common.RegisteredServiceInfo;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author darkness
 * @time 2022/3/7 11:15
 * @description
 */
public class FileRegister implements Register {

    @Override
    public void register(String group, String version, String interfaceName, String hostName, Integer port) {
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream("F:/registerCenter.txt", true);
            fileOut.write((group).getBytes(StandardCharsets.UTF_8));
            fileOut.write((" " + version).getBytes(StandardCharsets.UTF_8));
            fileOut.write((" " + interfaceName).getBytes(StandardCharsets.UTF_8));
            fileOut.write((" " + hostName).getBytes(StandardCharsets.UTF_8));
            fileOut.write((" " + port).getBytes(StandardCharsets.UTF_8));
            fileOut.write("\n".getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public RegisteredServiceInfo getService(String group, String version, String interfaceName) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("F:/registerCenter.txt")));
            String s;
            while ((s = bufferedReader.readLine()) != null) {
                String[] s1 = s.split(" ");
                String groupF = s1[0];
                String versionF = s1[1];
                String interfaceNameF = s1[2];
                String hostName = s1[3];
                String port = s1[4];
                if (group.equals(groupF) && version.equals(versionF) && interfaceName.equals(interfaceNameF)) {
                    return new RegisteredServiceInfo(hostName, Integer.parseInt(port));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

}
